#!/usr/bin/python2.4
#
#Copyright 2009 Google Inc.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
#

"""This module provides handlers for uploading data/images.

Data uploader runs in one-by-one mode. It reads metadata rows from db
one-by-one and prmpts user to upload the relevant document. In case of Image
upload, user is required to upload zip file of images. ImageUploadHandler,
unzips the given content and uploads the image files to db.
"""

import cgi
import cgitb
import logging
import os
import zipfile
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import base_request_handler
import constants
import  db_utils

cgitb.enable()
# Windows needs stdio set for binary mode.
try:
  import msvcrt
  # stdin  = 0
  msvcrt.setmode (0, os.O_BINARY)
  # stdout = 1
  msvcrt.setmode (1, os.O_BINARY)
except ImportError:
  logging.warning('didnt find msvcrt')


class FinishUploadHandler(base_request_handler.BaseRequestHandler):
  """Handler called when user clicks on 'Finish upload'."""

  def get(self):
    """GET method for this request handler."""
    db_handler = db_utils.DbHandler()
    db_handler.UpdateStatus(constants.IMAGE_UPLOAD)
    self.redirect('/create?status=' + constants.IMAGE_UPLOAD)


class ImageUploadHandler(base_request_handler.BaseRequestHandler):
  """Uploader that uploads images into db.

  This class receives the file given by the user.
  If it is a zip file, it unzips it and uploads all the files inside into db
  mapped to url /images/image_name.
  If it is a single file upload it to db directly mapped to url
  /images/image_name.
  """

  def post(self):
    """POST method for this request handler."""
    form = cgi.FieldStorage()
    file_item = form['file']
    db_handler = db_utils.DbHandler()
    if file_item.file:
      try:
        uploaded_file = zipfile.ZipFile(file_item.file, 'r')
        for filename in uploaded_file.namelist():
          image_url = constants.IMAGE_PATH + '/' + filename
          image_data = uploaded_file.read(filename)
          db_handler.AddImage(image_url, image_data)
      except zipfile.error:
        logging.warning(
            'Error while treating file %s as zipfile',
            file_item.filename)
        # Upload the file as it is.
        image_url = constants.IMAGE_PATH + '/' + file_item.filename
        logging.debug('image_url:' + image_url)
        image_data = file_item.file.read()
        db_handler.AddImage(image_url, image_data)

    db_handler.UpdateStatus(constants.GENERATE_WEBSITE)
    self.redirect('/create?status=' + constants.GENERATE_WEBSITE)


application = webapp.WSGIApplication(
    [('/finishupload', FinishUploadHandler),
     ('/imageupload', ImageUploadHandler)],
    debug=True)


def main():
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
